(function() {
	var log = panda.log("servlets.api");
	var error = 'API Servlet Error: "{}", when excuting {}.{}() with params: {}';

	var servlet = javax.servlet.http.HttpServlet;
	servlets.api = servlet({ service: service });

	function service(req, res) {
		var result = run(req, res);
		if (result !== null) {
			res.contentType = "text/html; charset=UTF8";
			res.writer.write(JSON.stringify(result));
		}
	}

	function run(req, res) {
		var ret, reqString,
			request, actionString, params,
			parts, controller, action;

		try {		
			reqString = req.getParameter("request");
	
			if (reqString) {
				request = JSON.parse(reqString);
				actionString = request.action;
				params = request.params;
			} else {
				actionString = req.getParameter("action") + "";
			}
	
			parts = actionString.split(".");
			controller = parts[0];
			action = parts[1];
	
			var proxy = panda.proxy("api." + controller);
			var data = proxy[action](params, req, res);

			if (data === null) {
				return null;
			} else if (data === undefined) {
				return { success: true };
			} else {
				return { data : data, success : true }
			}
		} catch(e) {
			params = JSON.stringify(params) + "";
			log.error(error, [e, controller + "", action + "", params]);
			return { error: e.toString(), success: false }
		}
	}
}());
